package com.yzdbx.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.DbUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yzdbx.task.ProductOrderRunnable.GEN_PRODUCT_ORDER_IDS;
import static com.yzdbx.task.ProductPlanRunnable.GEN_PRODUCT_PLAN_IDS;
import static com.yzdbx.utils.DbUtil.getById;
import static com.yzdbx.utils.DbUtil.getMaxId;
import static com.yzdbx.utils.GenUtil.getNo;
import static com.yzdbx.utils.GenUtil.getNoFromTable;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: 生产入库
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class FinishProductIntoRunnable implements Exe {


    private Connection connection;


    public FinishProductIntoRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) throws SQLException {
        List<Integer> orderIds = GEN_PRODUCT_ORDER_IDS.get();
        if (CollectionUtil.isEmpty(orderIds)) return Boolean.TRUE;

        try {
            int maxId = getMaxId(connection, "ck03Listing");
            int maxIdDetail = getMaxId(connection, "ck04ListOfEntriesListOfEntries");
            for (Integer orderId : orderIds) {
                Map<String, Object> order = getById(connection, "missionInformationSc02", orderId);
                PreparedStatement statement = connection.prepareStatement("insert into ck03Listing (id,documentType,repositoryNumber,operator,repositoryDate,approvalStatus) values (?,?,?,?,?,?)");
                statement.setInt(1, ++maxId);
                statement.setString(2, "生产入库");
                statement.setString(3, getNoFromTable(connection,"CK", "ck03Listing","repositoryNumber"));
                statement.setString(4, order.get("officerincharge").toString());
                statement.setDate(5, (Date) order.get("actualEndDate"));
                statement.setString(6, "已通过");
                statement.execute();

                statement = connection.prepareStatement("insert into ck04ListOfEntriesListOfEntries(id,productInformation,numberOfEntries,linkToList)values (?,?,?,?)");
                statement.setInt(1, ++maxIdDetail);
                statement.setInt(2, Integer.parseInt(order.get("productName").toString()));
                statement.setBigDecimal(3, new BigDecimal(order.get("numberOfTasks").toString()));
                statement.setInt(4, maxId);
                statement.execute();
            }
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }


        return Boolean.TRUE;
    }


}
